package org.jeecg.chase.modules.order.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.chase.modules.order.entity.AdhCouponOrder;
import org.jeecg.chase.modules.order.service.IAdhCouponOrderService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: adh_coupon_order
 * @Author: jeecg-boot
 * @Date: 2022-03-05
 * @Version: V1.0
 */
@Api(tags = "adh_coupon_order")
@RestController
@RequestMapping("/order/adhCouponOrder")
@Slf4j
public class AdhCouponOrderController extends JeecgController<AdhCouponOrder, IAdhCouponOrderService> {
    @Autowired
    private IAdhCouponOrderService adhCouponOrderService;

    private String exportTempFilePath = System.getProperty("java.io.tmpdir") + File.separator + "adhAdmin";

    /**
     * 分页列表查询
     *
     * @param adhCouponOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "adh_coupon_order-分页列表查询")
    @ApiOperation(value = "adh_coupon_order-分页列表查询", notes = "adh_coupon_order-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AdhCouponOrder adhCouponOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<AdhCouponOrder> queryWrapper = QueryGenerator.initQueryWrapper(adhCouponOrder, req.getParameterMap());
        Page<AdhCouponOrder> page = new Page<AdhCouponOrder>(pageNo, pageSize);
        IPage<AdhCouponOrder> pageList = adhCouponOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "adh_coupon_order-报名券列表查询")
    @ApiOperation(value = "adh_coupon_order-报名券列表查询", notes = "adh_coupon_order-报名券列表查询")
    @GetMapping(value = "/list2")
    public Result<?> queryPageList2(AdhCouponOrder adhCouponOrder,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {
        QueryWrapper<AdhCouponOrder> queryWrapper = QueryGenerator.initQueryWrapper(adhCouponOrder, req.getParameterMap());
        queryWrapper.eq("coupon_type", "5");
        Page<AdhCouponOrder> page = new Page<AdhCouponOrder>(pageNo, pageSize);
        IPage<AdhCouponOrder> pageList = adhCouponOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @AutoLog(value = "adh_coupon_order-分页列表查询")
    @ApiOperation(value = "adh_coupon_order-分页列表查询", notes = "adh_coupon_order-分页列表查询")
    @GetMapping(value = "/merchList")
    public Result<?> merchList(AdhCouponOrder adhCouponOrder,
                               HttpServletRequest req) {
        QueryWrapper<AdhCouponOrder> queryWrapper = QueryGenerator.initQueryWrapper(adhCouponOrder, req.getParameterMap());
        queryWrapper.eq("merch_id", adhCouponOrder.getMerchId());
        queryWrapper.eq("use_status", 1);

        List<AdhCouponOrder> list = adhCouponOrderService.list(queryWrapper);
        return Result.OK(list);
    }

    /**
     * 添加
     *
     * @param adhCouponOrder
     * @return
     */
    @AutoLog(value = "adh_coupon_order-添加")
    @ApiOperation(value = "adh_coupon_order-添加", notes = "adh_coupon_order-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AdhCouponOrder adhCouponOrder) {
        adhCouponOrderService.save(adhCouponOrder);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param adhCouponOrder
     * @return
     */
    @AutoLog(value = "adh_coupon_order-编辑")
    @ApiOperation(value = "adh_coupon_order-编辑", notes = "adh_coupon_order-编辑")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody AdhCouponOrder adhCouponOrder) {
        adhCouponOrderService.updateById(adhCouponOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "adh_coupon_order-通过id删除")
    @ApiOperation(value = "adh_coupon_order-通过id删除", notes = "adh_coupon_order-通过id删除")
    @GetMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        adhCouponOrderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "adh_coupon_order-批量删除")
    @ApiOperation(value = "adh_coupon_order-批量删除", notes = "adh_coupon_order-批量删除")
    @GetMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.adhCouponOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "adh_coupon_order-通过id查询")
    @ApiOperation(value = "adh_coupon_order-通过id查询", notes = "adh_coupon_order-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AdhCouponOrder adhCouponOrder = adhCouponOrderService.getById(id);
        if (adhCouponOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(adhCouponOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param adhCouponOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AdhCouponOrder adhCouponOrder) {
        return super.exportXls(request, adhCouponOrder, AdhCouponOrder.class, "adh_coupon_order");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AdhCouponOrder.class);
    }


    @AutoLog(value = "adh_coupon_order-报名券列导出")
    @ApiOperation(value = "adh_coupon_order-报名券列导出", notes = "adh_coupon_order-报名券列导出")
    @GetMapping(value = "/preExport")
    public Result<?> preExport(AdhCouponOrder adhCouponOrder,
                               HttpServletRequest req) {
        QueryWrapper<AdhCouponOrder> queryWrapper = QueryGenerator.initQueryWrapper(adhCouponOrder, req.getParameterMap());
        queryWrapper.eq("coupon_type", "5");

        Result<String> result = new Result<String>();
        ExcelWriter excelWriter = null;
        OutputStream outputStream = null;
        try {
            log.info("报名券列Excel导出---开始");
            if (!new File(exportTempFilePath).exists()) {
                new File(exportTempFilePath).mkdirs();
            }
            String fileName = "adh_coupon_order_5" + System.currentTimeMillis();
            String filePath = this.exportTempFilePath + File.separator + fileName + ".xlsx";
            outputStream = new FileOutputStream(new File(filePath));
            ClassPathResource classPathResource = new ClassPathResource("templates/AdhCouponOrder5.xlsx");
            InputStream inputStream = classPathResource.getInputStream();
            excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            Page<AdhCouponOrder> pageTotal = adhCouponOrderService.page(new Page<AdhCouponOrder>(1, 1), queryWrapper);
            long total = pageTotal.getTotal();
            long maxNum = 2000;
            long num = (total / maxNum) + 1;
            for (int i = 0; i < num; i++) {
                log.info("报名券列Excel导出---查询数据第" + (i + 1) + "批数据，每批最多" + maxNum + "条数据");
                Page<AdhCouponOrder> page = adhCouponOrderService.page(new Page<AdhCouponOrder>((i + 1), maxNum), queryWrapper);
                List<AdhCouponOrder> listData = page.getRecords();
                excelWriter.fill(listData, writeSheet);
                listData.clear();
                listData = null;
            }
            result.setResult(fileName);
            log.info("报名券列Excel导出---结束");

        } catch (Exception e) {
            e.printStackTrace();
            result.error500("Excel生成失败");
        } finally {
            try {
                if (excelWriter != null) {
                    excelWriter.finish();
                    excelWriter = null;
                }
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                    outputStream = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                result.error500("Excel生成失败");
            }
            System.gc();
        }
        return result;
    }

    @RequestMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam("name") String name,
                       @RequestParam("path") String path) throws Exception {
        String filePath = this.exportTempFilePath + File.separator + path + ".xlsx";
        if (!new File(filePath).exists()) {
            filePath = this.exportTempFilePath + File.separator + path + ".xlsx";
        }
        try {
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=\"" + new String((name + ".xlsx").getBytes("GBK"), "ISO8859-1") + "\"");
            OutputStream outputStream = response.getOutputStream();
            InputStream inputStream = new FileInputStream(filePath);
            int byteread = 0;
            byte[] filedata = new byte[1024];
            while ((byteread = inputStream.read(filedata)) != -1) {
                outputStream.write(filedata, 0, byteread);
            }
            inputStream.close();
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                new File(filePath).delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
